﻿using AuroraPlatform.TCP;
using AuroraPlatform.Tools;
using AuroraPlatform.View.Level5;
using AuroraPlatform.ViewModel;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Browser;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Threading;

namespace AuroraPlatform.View.Level3
{
    public partial class LightingListView : UserControl, IPageProvider, IExportData
    {
        private ObservableCollection<LightingListModel> _items = new ObservableCollection<LightingListModel>();
        private ColumnDefinition _firstColumn = null;
        private bool _isCheckedStatus = false;

        public void ShowChecked()
        {
            _isCheckedStatus = true;
            foreach (LightingListModel model in _items)
            {
                model.Visibility = Visibility.Visible;
            }
        }

        public void ShowUnChecked()
        {
            _isCheckedStatus = false;
            foreach (LightingListModel model in _items)
            {
                model.Visibility = Visibility.Collapsed;
                model.IsChecked = false;
            }
        }

        public void SetAllChecked()
        {
            foreach (LightingListModel model in _items)
            {
                model.IsChecked = true;
            }
        }

        public void ClearChecked()
        {
            foreach (LightingListModel model in _items)
            {
                model.IsChecked = false;
            }
        }

        public async void BatchDeleted()
        {
            var query = from r in _items
                        where r.IsChecked
                        select r;

            StringBuilder sb = new StringBuilder();
            int index = 0;
            foreach (LightingListModel model in query)
            {
                index++;
                sb.AppendFormat("{0},", model.ID);
            }

            if (index == 0)
            {
                MessageHelper.ShowMessage("未选择任何数据。");
                return;
            }

            string message = string.Format("确定删除选择的【{0}】条数据？", index);
            if (!MessageHelper.Confirm(message))
                return;

            BatchDelete.Builder builder = new BatchDelete.Builder();
            builder.SetId(sb.Remove(sb.Length - 1, 1).ToString());

            busy.BusyContent = "正在删除数据，请稍等......";
            busy.IsBusy = true;
            WebServiceProxy proxy = new WebServiceProxy();
            bool result = await proxy.BatchDeleteProd(builder.Build().ToByteArray());
            busy.IsBusy = false;

            if (result)
            {
                MessageHelper.ShowMessage(string.Format("成功删除【{0}】条数据。", index));
                List<LightingListModel> list = new List<LightingListModel>();
                list.AddRange(query);

                foreach (LightingListModel item in list)
                {
                    _items.Remove(item);
                }
            }
            else
            {
                MessageHelper.ShowError("批量删除数据失败。");
            }
        }
    
        public LightingListView()
        {
            InitializeComponent();

            for (int i = 0; i < 2; i++)
            {
                TitleGrid.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(23) });
            }

            _firstColumn = new ColumnDefinition() { Width = new GridLength(70) };
            TitleGrid.ColumnDefinitions.Add(_firstColumn);
            for (int i = 0; i < 10; i++)
            {
                TitleGrid.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(i == 4 ? 220 : 75) });
            }
            

            TitleGrid.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(155) });

            AddTable(CreateLighting(), 0);
            AddTable(CreateSource(), 6);
            AddTable(CreateOptics(), 10);
            AddTable(CreateBusiness(), 11);

            DataGrid.SelectionChanged += DataGrid_SelectionChanged;
            DataGrid.ItemsSource = _items;
            Loading();
        }

        private void DataGrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            LightingListModel lighting = (LightingListModel)DataGrid.SelectedItem;
            if (lighting != null)
            {
                if (_isCheckedStatus)
                {
                    lighting.IsChecked = !lighting.IsChecked;
                }
                else
                {
                    BusinessContext.Singleton.ParamIterator.GoNew(
                        new NaviTo4Param()
                        { 
                            ID = lighting.ID,
                            CurrentUrl = MainPage.Level4Uri
                            //SourceUrl = MainPage.Level3Uri
                        });
                    Navigation.Navigate(new Uri(MainPage.Level4Uri, UriKind.RelativeOrAbsolute));
                }
            }
        }

        private LightingListModel ConvertForm(ProdView lighting)
        {
            LightingListModel vm = new LightingListModel();
            vm.ID = lighting.Id;

            if(!string.IsNullOrEmpty(lighting.PicFacade))
                vm.PicFacade = BusinessContext.Singleton.ImageUrl + lighting.PicFacade;

            vm.ProdSeries = lighting.ProdSeries;
            vm.ProdClass = lighting.ProdClass;
            vm.ProdVersion = lighting.ProdVersion;
            vm.ProdLabel = lighting.ProdLabel;
            vm.PhySize = lighting.PhySize;
            vm.AdpClass = lighting.AdpClass;
            vm.EleLgtPower = lighting.EleLgtPower;
            vm.AdpColor = lighting.AdpColor;
            vm.AdpCri = lighting.AdpCri;
            vm.OptAngle = lighting.OptAngle;
            vm.BusMarket = lighting.BusMarket;
            return vm;
        }

        public async void Loading()
        {
            _items.Clear();
            busy.IsBusy = true;
            busy.BusyContent = "正在加载数据，请稍等......";
            
            ProdViewArray array = null;
            WebServiceProxy proxy = new WebServiceProxy();
            NaviToParam parameter = BusinessContext.Singleton.ParamIterator.Current;
            if (parameter is SearchNaviToParam)
            {
                SearchNaviToParam searchNaviToParam = (SearchNaviToParam)parameter;
                array = await proxy.SearchProdList(searchNaviToParam.Parameter.ToByteArray());
            }
            else if (parameter is NaviTo3Param)
            {
                NaviTo3Param naviTo3Param = (NaviTo3Param)parameter;
                array = await proxy.SearchProdSeries(naviTo3Param.Parameter.ToByteArray());
            }
            else if (parameter is NaviTo1MonthParam)
            {
                array = await proxy.SearchNewProds();
            }

            busy.IsBusy = false;
            if (array != null)
            {
                NaviToParam previous = parameter.Next;
                if (previous is NaviTo4Param)
                {
                    NaviTo4Param naviTo4Param = (NaviTo4Param)previous;

                    foreach (ProdView lighting in array.ViewList)
                    {
                        LightingListModel model = ConvertForm(lighting);
                        _items.Add(model);

                        if (lighting.Id == naviTo4Param.ID)
                        {
                            DataGrid.SelectionChanged -= DataGrid_SelectionChanged;
                            DataGrid.SelectedItem = model;
                            try
                            {
                                this.DataGrid.ScrollIntoView(model, this.DataGrid.Columns[this.DataGrid.Columns.Count - 1]);
                            }
                            catch
                            {
                            }
                            DataGrid.SelectionChanged += DataGrid_SelectionChanged;
                        }
                    }
                }
                else
                {
                    foreach (ProdView lighting in array.ViewList)
                    {
                        _items.Add(ConvertForm(lighting));
                    }
                }
            }
        }

        public async void ExportToExcel()
        {
            WebServiceProxy proxy = new WebServiceProxy();
            NaviToParam parameter = BusinessContext.Singleton.ParamIterator.Current;
            string url = null;
            busy.BusyContent = "正在导出数据，请稍等......";
            if (parameter is SearchNaviToParam)
            {
                SearchNaviToParam searchNaviToParam = (SearchNaviToParam)parameter;
                url = await proxy.SearchProdListToExcel(searchNaviToParam.Parameter.ToByteArray());
            }
            else if (parameter is NaviTo3Param)
            {
                NaviTo3Param naviTo3Param = (NaviTo3Param)parameter;
                url = await proxy.SearchProdSeriesToExcel(naviTo3Param.Parameter.ToByteArray());
            }
            else if (parameter is NaviTo1MonthParam)
            {
                url = await proxy.SearchNewProdsToExcel();
            }

            busy.IsBusy = false;
            if (!string.IsNullOrEmpty(url))
                HtmlPage.Window.Navigate(new Uri(url));
            else
                MessageHelper.ShowError("导出数据出错。");
        }

        public async void ExportToPdf()
        {
            WebServiceProxy proxy = new WebServiceProxy();
            NaviToParam parameter = BusinessContext.Singleton.ParamIterator.Current;
            string url = null;
            busy.BusyContent = "正在导出数据，请稍等......";
            if (parameter is SearchNaviToParam)
            {
                SearchNaviToParam searchNaviToParam = (SearchNaviToParam)parameter;
                url = await proxy.SearchProdListToPDF(searchNaviToParam.Parameter.ToByteArray());
            }
            else if (parameter is NaviTo3Param)
            {
                NaviTo3Param naviTo3Param = (NaviTo3Param)parameter;
                url = await proxy.SearchProdSeriesToPDF(naviTo3Param.Parameter.ToByteArray());
            }
            else if (parameter is NaviTo1MonthParam)
            {
                url = await proxy.SearchNewProdsToPDF();
            }

            busy.IsBusy = false;
            if (!string.IsNullOrEmpty(url))
                HtmlPage.Window.Navigate(new Uri(url));
            else
                MessageHelper.ShowError("导出数据出错。");
        }

        private void SetTimer()
        {
            DispatcherTimer timer = new DispatcherTimer();
            timer.Interval = TimeSpan.FromMinutes(20);
            timer.Tick += timer_Tick;
            timer.Start();
        }

        private void timer_Tick(object sender, EventArgs e)
        {
            DispatcherTimer timer = (DispatcherTimer)sender;
            timer.Stop();
            if (busy.IsBusy)
            {
                busy.IsBusy = false;
                MessageHelper.ShowError("服务器响应超时，请重新操作。");
                return;
            }
        }

        private void AddTable(LightingTable table, int columnIndex)
        {
            SolidColorBrush brush = new SolidColorBrush(table.Backgroud);

            Grid tableTitle = CreateTitleCell(table.Name, 0, columnIndex, 14);
            tableTitle.Background = brush;
            TitleGrid.Children.Add(tableTitle);
            Grid.SetColumn(tableTitle, columnIndex);
            Grid.SetColumnSpan(tableTitle, table.Columns.Length);

            int startColumnIndex = 0;
            foreach (ColumnProperty column in table.Columns)
            {
                Grid columnTitle = CreateTitleCell(column.Name, 1, startColumnIndex + columnIndex);
                columnTitle.Background = brush;
                TitleGrid.Children.Add(columnTitle);
                Grid.SetRow(columnTitle, 1);
                Grid.SetColumn(columnTitle, startColumnIndex + columnIndex);

                startColumnIndex++;
            }
        }

        private Grid CreateTitleCell(string text, int rowIndex, int columIndex, double fontsize = 13)
        {
            Grid grid = new Grid();

            Border border = new Border();
            border.BorderBrush = new SolidColorBrush(Colors.White);

            if (rowIndex == 0)
            {
                if (columIndex > 0)
                {
                    border.BorderThickness = new Thickness(1, 0, 0, 0);
                }
                else
                {
                    border.BorderThickness = new Thickness(0);
                }
            }
            else
            {
                if (columIndex == 0)
                {
                    border.BorderThickness = new Thickness(0, 1, 0, 0);
                }
                else
                {
                    border.BorderThickness = new Thickness(1, 1, 0, 0);
                }
            }

            grid.Children.Add(border);

            TextBlock tb = new TextBlock();
            tb.Text = text;
            tb.FontSize = fontsize;
            tb.HorizontalAlignment = HorizontalAlignment.Center;
            tb.VerticalAlignment = VerticalAlignment.Center;

            grid.Children.Add(tb);
            return grid;
        }

        public LightingTable CreateLighting()
        {
            return new LightingTable()
            {
                Name = "产品描述",
                Columns = new ColumnProperty[]
                {
                    new ColumnProperty { Name = "产品图片" },
                    new ColumnProperty { Name = "产品系列" },
                    new ColumnProperty { Name = "产品分类" },
                    new ColumnProperty { Name = "规格型号" },
                    new ColumnProperty { Name = "产品品牌" },
                    new ColumnProperty { Name = "外形尺寸" },
                },
                Backgroud = Color.FromArgb(255, 234, 234, 234),
            };
        }

        public LightingTable CreateSource()
        {
            return new LightingTable()
            {
                Name = "光源描述",
                Columns = new ColumnProperty[]
                {
                    new ColumnProperty { Name = "光源种类" },
                    new ColumnProperty { Name = "光源功率" },
                    new ColumnProperty { Name = "光学色温" },
                    new ColumnProperty { Name = "显色性" },
                },
                Backgroud = Color.FromArgb(255, 204, 204, 204),
            };
        }

        public LightingTable CreateOptics()
        {
            return new LightingTable()
            {
                Name = "光学参数",
                Columns = new ColumnProperty[]
                {
                    new ColumnProperty { Name = "光束角" },
                },
                Backgroud = Color.FromArgb(255, 234, 234, 234)

            };
        }

        public LightingTable CreateBusiness()
        {
            return new LightingTable()
            {
                Name = "商务参数",
                Columns = new ColumnProperty[]
                {
                    new ColumnProperty { Name = "市场参考价"},
                },
                Backgroud = Color.FromArgb(255, 204, 204, 204)
            };
        }

        public PageLevel PageLevel
        {
            get { return PageLevel.Third; }
        }


        public INavigate Navigation
        {
            get;
            set;
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            Button btn = (Button)sender;
            LightingListModel item = btn.DataContext as LightingListModel;

            var query = from r in BusinessContext.Singleton.Items
                        where r.ID == item.ID
                        select r;

            if (query.Count() > 0)
                return;

            BusinessContext.Singleton.Items.Add(item);
            BusinessContext.Singleton.CartCount = BusinessContext.Singleton.Items.Count;
        }

        private void Button_MouseEnter(object sender, MouseEventArgs e)
        {
            DataGrid.SelectionChanged -= DataGrid_SelectionChanged;
            Button btn = (Button)sender;
            btn.CaptureMouse();
        }

        private void Button_MouseLeave(object sender, MouseEventArgs e)
        {
            DataGrid.SelectionChanged += DataGrid_SelectionChanged;
            Button btn = (Button)sender;
            btn.ReleaseMouseCapture();
        }
    }
}
